// user
const express = require("express");
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const router = express.Router();
const { getUserInfo, updateUserInfo, deleteUser } = require("../utils/sql");

// 确保上传目录存在
const uploadDir = path.join(__dirname, "../../uploads/avatars");
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置multer用于头像上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名：用户ID_时间戳.扩展名
    const ext = path.extname(file.originalname);
    const filename = `${req.body.user_id || 'user'}_${Date.now()}${ext}`;
    cb(null, filename);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 只允许图片文件
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('只允许上传图片文件'), false);
  }
};

const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 2 * 1024 * 1024 // 限制文件大小为2MB
  }
});

// 获取用户信息
router.post("/info", async (req, res) => {
  const { user_id } = req.body;
  try {
    const orders = await getUserInfo(user_id);
    res.send({ code: 200, message: "获取成功", orders });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "获取失败" });
  }
});

// 更新用户信息
router.post("/updateUser", async (req, res) => {
  console.log(req.body);
  const { user_id, username, password, full_name, phone_number, email, avatar } =
    req.body;
  try {
    await updateUserInfo(
      user_id,
      username,
      password,
      full_name,
      phone_number,
      email,
      avatar
    );
    res.send({ code: 200, message: "更新成功" });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "更新失败" });
  }
});

// 上传头像
router.post("/uploadAvatar", upload.single('avatar'), async (req, res) => {
  try {
    if (!req.file) {
      return res.send({ code: 0, message: "请选择要上传的图片" });
    }

    const { user_id } = req.body;
    if (!user_id) {
      return res.send({ code: 0, message: "用户ID不能为空" });
    }

    // 构建头像URL
    const avatarUrl = `/uploads/avatars/${req.file.filename}`;

    // 更新数据库中的头像字段
    await updateUserInfo(user_id, null, null, null, null, null, avatarUrl);

    res.send({
      code: 200,
      message: "头像上传成功",
      data: {
        avatarUrl: avatarUrl
      }
    });
  } catch (err) {
    console.error("头像上传失败:", err);
    res.send({ code: 0, message: "头像上传失败" });
  }
});

// 删除用户
router.post("/deleteUser", async (req, res) => {
  console.log(req.body);
  const { user_id } = req.body;
  if (user_id === 17) {
    res.send({ code: 0, message: "管理员不能注销" });
    return;
  }
  try {
    await deleteUser(user_id);
    res.send({ code: 200, message: "删除成功" });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "删除失败" });
  }
});

module.exports = router;
